<template>
    <a-drawer :open="openVisible" @close="onClose" :title="title" width="80%">
        <a-tabs v-model:activeKey="activeKey" @change="handleTabChange">
            <a-tab-pane key="1" tab="字段">
                <table-field ref="tableFieldRef" :table_name="table_name" @change:table_name="(fields) => {
                    table_save.fields = fields
                }" />
            </a-tab-pane>
            <a-tab-pane key="2" tab="索引">
                <IndexField ref="indexRef" :table_name="table_name" :fields="table_save.fields" @change:table_name="(fields) => {
                    table_save.fields = fields
                }" />
            </a-tab-pane>
            <a-tab-pane key="3" tab="外键">
                <ForeignKey ref="foreignKeyRef" :table_name="table_name" :fields="table_save.fields" @change:table_name="(fields) => {
                    table_save.fields = fields
                }" />
            </a-tab-pane>
            <a-tab-pane key="4" tab="触发器">
                <Trigger ref="triggerRef" :table_name="table_name" :fields="table_save.fields" @change:table_name="(fields) => {
                    table_save.fields = fields
                }" />
            </a-tab-pane>
            <a-tab-pane key="5" tab="选项">
                <Option ref="optionRef" :table_name="table_name" :fields="table_save.fields" @change:table_name="(fields) => {
                    table_save.fields = fields
                }" />
            </a-tab-pane>
            <a-tab-pane key="6" tab="注释">Content of Tab Pane 6</a-tab-pane>
            <a-tab-pane key="7" tab="SQL预览">
                <pre>{{ sqlPreview }}</pre>

                {{ table_save.fields }}
            </a-tab-pane>
        </a-tabs>


        <template #footer>
            <div class="flex justify-end">
                <a-space>
                    <a-button @click="handleSave">保存</a-button>
                    <a-button type="primary" @click="onClose">关闭</a-button>
                </a-space>
            </div>
        </template>
    </a-drawer>
</template>

<script setup lang="ts">
import request from '@/utils/request'
import { useRequest } from 'vue-request'
import TableField from './tableField.vue'
import IndexField from './indexs.vue'
import ForeignKey from './foreugn_key.vue'
import Trigger from './trigger.vue'
import Option from './option.vue'
import { ref, computed, watch } from 'vue'

const openVisible = ref(false)
const activeKey = ref('1')
const table_name = ref<string>('')
const tableFieldRef = ref()

const title = computed(() => {
    return `字段设置 - ${table_name.value}`
})

const api = (data?: any) => request.post({ url: '/adminapi/system.setting.database/set_table_update', data })

const table_save = reactive({
    table_name: '',
    
    fields: []
})

const handleSave = async () => {
    const res = await api({
        table_name: table_save.table_name,
        fields: table_save.fields
    })
    console.log(res)
}
const open = (tableName?: string) => {
    table_name.value = tableName || ''
    table_save.table_name = tableName || ''
    openVisible.value = true
}

const onClose = () => {
    openVisible.value = false
    activeKey.value = '1'
}

// 处理 tab 切换
const handleTabChange = (key: string) => {
    if (key === '1' && tableFieldRef.value && !tableFieldRef.value.isLoaded()) {
        tableFieldRef.value.refresh()
    }
}

// 监听 drawer 打开状态
watch(
    () => openVisible.value,
    (newVal) => {
        if (newVal && tableFieldRef.value) {
            tableFieldRef.value.refresh()
        }
    }
)

const sqlPreview = computed(() => {
    if (!table_save.fields || !table_save.fields.length) return ''
    const fields = table_save.fields
    const options = table_save.options || {}
    const tableName = table_save.table_name || 'table_name'

    // 字段定义
    const fieldLines = fields.map(f => {
        let line = `  \`${f.column_name}\``
        // 类型
        if (f.type) {
            if (["decimal", "float", "double"].includes(f.type) && f.length) {
                line += ` ${f.type}(${f.length}${f.scale ? ',' + f.scale : ''})`
            } else if (f.length) {
                line += ` ${f.type}(${f.length})`
            } else {
                line += ` ${f.type}`
            }
        }
        // unsigned
        if (f.unsigned) line += ' unsigned'
        // null
        line += f.is_nullable === 'NO' ? ' NOT NULL' : ' NULL'
        // auto_increment
        if (f.extra && f.extra.includes('auto_increment')) line += ' AUTO_INCREMENT'
        // default
        if (f.column_default !== undefined && f.column_default !== null && f.column_default !== '') {
            if (typeof f.column_default === 'string') {
                line += ` DEFAULT '${f.column_default}'`
            } else {
                line += ` DEFAULT ${f.column_default}`
            }
        }
        // comment
        if (f.column_coment) line += ` COMMENT '${f.column_coment}'`
        return line
    })

    // 主键、唯一、索引
    const pk = fields.filter(f => f.column_key === 'PRI').map(f => `\`${f.column_name}\``)
    const unique = fields.filter(f => f.column_key === 'UNI').map(f => `UNIQUE KEY \`${f.column_name}\` (\`${f.column_name}\`)`)
    const index = fields.filter(f => f.column_key === 'MUL').map(f => `KEY \`${f.column_name}\` (\`${f.column_name}\`)`)

    // 组合所有行
    let lines = [...fieldLines]
    if (pk.length) lines.push(`  PRIMARY KEY (${pk.join(', ')})`)
    if (unique.length) lines.push('  ' + unique.join(',\n  '))
    if (index.length) lines.push('  ' + index.join(',\n  '))

    // 表选项
    let tableOptions = []
    if (options.engine) tableOptions.push(`ENGINE=${options.engine}`)
    if (options.auto_increment) tableOptions.push(`AUTO_INCREMENT=${options.auto_increment}`)
    if (options.charset) tableOptions.push(`DEFAULT CHARSET=${options.charset}`)
    if (options.collation) tableOptions.push(`COLLATE=${options.collation}`)
    if (options.comment) tableOptions.push(`COMMENT='${options.comment}'`)

    // 触发器
    let triggerSql = ''
    if (table_save.triggers && table_save.triggers.length) {
        triggerSql = table_save.triggers.map(t => {
            let events = []
            if (t.event_insert) events.push('INSERT')
            if (t.event_update) events.push('UPDATE')
            if (t.event_delete) events.push('DELETE')
            return events.map(ev =>
                `CREATE TRIGGER \`${t.name}\` BEFORE ${ev} ON \`${tableName}\` FOR EACH ROW\nBEGIN\n  -- 触发器内容\nEND;`
            ).join('\n')
        }).join('\n\n')
    }

    return (
        `CREATE TABLE \`${tableName}\` (\n${lines.join(',\n')}\n)${tableOptions.length ? ' ' + tableOptions.join(' ') : ''};`
        + (triggerSql ? '\n\n' + triggerSql : '')
    )
})

defineExpose({
    open
})
</script>
